package com.cgc.venus.server.job.service;
import com.cgc.venus.server.core.base.AbstractBaseService;
import com.cgc.venus.server.core.exception.VenusException;
import com.cgc.venus.server.job.inter.EmailService;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Service;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;


@Service
@ConfigurationProperties(prefix = "email")
public class EmailServiceImpl extends AbstractBaseService implements EmailService{
    private static final Logger logger = LogManager.getLogger(EmailServiceImpl.class);
    private String host;
    private String fromUsername;
    private String fromPassword;
    public String getHost() {
        return host;
    }
    public void setHost(String host) {
        this.host = host;
    }
    public String getFromUsername() {
        return fromUsername;
    }
    public void setFromUsername(String fromUsername) {
        this.fromUsername = fromUsername;
    }
    public String getFromPassword() {
        return fromPassword;
    }
    public void setFromPassword(String fromPassword) {
        this.fromPassword = fromPassword;
    }
    @Override
    public boolean sendEmailByText(String[] toAddrs, String topic, String text) throws VenusException {
        try{
            if(toAddrs==null||toAddrs.length==0){
                return false;
            }
            //1.发送邮件
            Properties prop = new Properties();
            //prop.setProperty("mail.smtp.auth","true");
            Session session = Session.getInstance(prop, null);
            session.setDebug(false);
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(fromUsername));
            message.setText(text);
            message.setSubject(topic);

            InternetAddress[] addresses = new InternetAddress[toAddrs.length];
            for (int i = 0; i < toAddrs.length; i++) {
                addresses[i] = new InternetAddress(toAddrs[i]);
            }
            message.setRecipients(Message.RecipientType.TO, addresses);
            Transport transport = session.getTransport("smtp");
            transport.connect(host,fromUsername,fromPassword);
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
            return true;
        }catch (Exception ex){
            logger.error(ex.getMessage(),ex);
        }
        return false;
    }
}